﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity.Infrastructure;
using System.Data.Entity;
using System.Data;
using XAPI.Domain;

namespace XAPI.Data
{
    /// <summary>
    /// http://jason-mitchell.com/software-development/data-access-using-a-generic-repository-in-c/
    /// </summary>
    public class EFRepository : IRepository, IDisposable
    {
        EFContext context;

        public EFRepository()
        {
            context = new EFContext();
        }

        public IQueryable<T> Query<T>(System.Linq.Expressions.Expression<Func<T, bool>> filter = null) where T : class
        {
            IQueryable<T> query = context.Set<T>();

            if (filter != null)
                query = query.Where(filter);

            return query;
        }

        public T SingleOrDefault<T>(System.Linq.Expressions.Expression<Func<T, bool>> predicate) where T : class
        {
            return context.Set<T>().SingleOrDefault(predicate);
        }

        public void Insert<T>(T entity) where T : class
        {
            context.Set<T>().Add(entity);
            context.SaveChanges();
        }

        public void Update<T>(T entity) where T : class
        {
            var entityEntry = context.Entry(entity);
            if (entityEntry.State == EntityState.Detached)
            {
                context.Set<T>().Attach(entity);
                entityEntry.State = EntityState.Modified;
            }
        }

        public void AddOrModify<T>(T entity, string key) where T : class, IEntity // Implements MyKey 
        {
            if (context.Set<T>().Any(e => e.Key == key))
            {
                context.Entry(entity).State = EntityState.Modified;
            }
            else
            {
                context.Entry(entity).State = EntityState.Added;
            }

            context.SaveChanges();
        }

        public void Delete<T>(T entity) where T : class
        {
            context.Set<T>().Remove(entity);
        }

        public void Dispose()
        {
            context.Dispose();
        }
    }
}
